package com.tsq.file.provider.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @Author：ly
 * @Description:
 * @Date: 2020/6/29 0029 下午 5:12
 */
@Slf4j
public class Base64Utils {
    /**
     * base64 格式转化为 MultipartFile
     * @param base64 字符串
     * （base64格式: "data:image/png;base64," + "图片的base64字符串"）
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64){
        try {
            String[] baseStr = base64.split(",");
            Base64 decoder = new Base64();
            byte[] b = new byte[0];
            b = decoder.decode(baseStr[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b,baseStr[0]);
        }catch (Exception e){
            e.printStackTrace();
            log.info(e.getMessage());
            return null;
        }
    }
}
